<?php
/**
 * Sms Model
 *
 * @property Item
 */
class SmsMeta extends AppModel {
/**
 * Display field
 *
 * @var string
 */


    var $hasMany = array(
        'SmsOutbox' => array(
            'className' => 'SmsOutbox',
            'foreignKey' => 'sms_meta_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        )
    );

    var $belongsTo = array(
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'user_id',
            'conditions' => '',
            'order' => '',
            'limit' => '',
            'dependent' => false
        )
    );


    function deleteScheduledSMS($ids,$user_id){
        $delete_outboxes_ids = array();
        $model_sms_outboxes = ClassRegistry::init('SmsOutbox');
        foreach($ids as $id){
            $cur_time=date("Y-m-d H:i:s");
            $duration='+5 minutes';
            $compare_date =  date('Y-m-d H:i:s', strtotime($duration, strtotime($cur_time)));
            $condition_array = array(
                'SmsMeta.id' => $id,
                'SmsMeta.user_id' => $user_id,
                'SmsMeta.schedule' => 'Later',
                'SmsMeta.schedule_date > ' => $compare_date,
                'SmsMeta.deleted' => 'n'
            );
            $meta = $this->find('first', array(
                'conditions' => $condition_array,
                'recursive' => -1
            ));
            if($meta){
                $this->updateAll(
                    array('SmsMeta.deleted' => "'y'"),
                    array('SmsMeta.id' => $id)
                );
                $model_sms_outboxes->updateAll(
                    array('SmsOutbox.deleted' => "'y'"),
                    array('SmsOutbox.sms_meta_id' => $id)
                );
                $delete_outboxes_id[] = $id;
                //Credit the user account
                $user_model = ClassRegistry::init('User');
                $amt = $meta['SmsMeta']['cost'];
                $user_model->addCredit($user_id,$amt);
            }
        }

        return true;
    }

}
